package be.groept.ace.enquete.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.Survey;
import be.groept.ace.enquete.model.dao.DAOCommand;
import be.groept.ace.enquete.model.dao.DAOFactory;
import be.groept.ace.enquete.model.dao.DAOManager;
import be.groept.ace.enquete.model.exceptions.DAOException;

/**
 * Servlet implementation class EnqueteServlet
 */
@WebServlet("/user/enquete/*")
public class EnqueteServlet extends UserServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(EnqueteServlet.class);

	@Override
	protected int handleGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession(false);
		String surveyIdString = request.getParameter("id");
		
		try {
			final int surveyId = Integer.parseInt(surveyIdString);
			DAOManager daoManager = null;
			try {
				daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
			} catch (DAOException daoe) {
				logger.fatal(daoe.toString());
				throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
			}
			Survey survey = (Survey)daoManager.transactionAndClose(new DAOCommand() {
				@Override
				public Object execute(DAOManager daoManager) throws DAOException {
					return daoManager.getSurveyDAO().findSurveyWithQuestionsAndCreator(surveyId);
				}
			});
			if (survey == null) {
				return 404;
			}
			session.setAttribute("survey", survey);
			addHeaderLink(request, 1, "Begin", response.encodeURL(request.getContextPath() + "/user/enquete/question?id=" + survey.getQuestionSet().first().getId()));
		} catch (NumberFormatException nfe) {
			logger.error("id moet een numerieke waarde zijn");
			return 404;
		} catch (DAOException daoe) {
			logger.error(daoe.toString());
			return 404;
		}
		setEnqueteViewAttributes(request, response);
		return 200;
	}

	@Override
	protected int handlePost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		return 404;
	}
	
	private void setEnqueteViewAttributes(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession(false);
		setForm(request, false);
		setPage(request, "enquete");
		setTitle(request, "Enquete: " + ((Survey)session.getAttribute("survey")).getTitle());
		setNavigationSelectedLink(request, ((Survey)session.getAttribute("survey")).getId());
	}
}
